﻿using ChestPainCenterSystem.Bll;
using ChestPainCenterSystem.Core;
using ChestPainCenterSystem.Model;
using ChestPainCenterSystem.ThreeCenterManage;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using ChestPainCenterSystem.Code.Bll;
using ChestPainCenterSystem.Utils;
using System.Configuration;

namespace ChestPainCenterSystem.Areas.ChestPainCenter.Controllers
{
    public class MedicalRecordsController : BaseController
    {
        // GET: /ChestPainCenter/MedicalRecords/
        [ValidateInput(false)]
        public ActionResult Index()
        {
            string patientId = WebUtils.GetString("patientId");
            ViewBag.patientId = patientId;
            GetDropRoomList();
            GetDropDocNurList();
            GetDropDoctorList();
            GetDropNurseList();
            return View();
        }
        
        /// <summary>
        /// 获取胸痛病历
        /// </summary>
        /// <param name="patientId"></param>
        /// <returns></returns>
        public ActionResult GetCaseHistory(string Pid)
        {
            OperateResult resultInfo = MedicalRecordsManager.GetCaseHistory(Pid);
            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 获取诊断路径列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPathNameList()
        {
            OperateResult resultInfo = PathwayManager.GetPathNameList();
            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 根据诊疗路径ID获取模板或内容
        /// </summary>
        /// <param name="pathId"></param>
        /// <returns></returns>
        public ActionResult GetDiagnosticPathTemp(int pathId, string patientId)
        {
            OperateResult resultInfo = PathwayManager.GetDiagnosticPathTemp(pathId, patientId);
            return JsonDate(resultInfo);
        }

        /// <summary>
        /// 修改胸痛病历
        /// </summary>
        /// <param name="patientId"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult SetCaseHistory(string ContentList)
        {
            string pid = Request["pidd"];
            OperateResult resultInfo = MedicalRecordsManager.GetCaseHistory(pid);
            string json = resultInfo.Body.ToString();
            SetCaseHistory PatHis = JsonConvert.DeserializeObject<SetCaseHistory>(json);
            if (PatHis == null) return Content("病历不存在");
            //获取三张图片原文件名
            string Image1_ADD_Old = PatHis.Image1_ADD;
            string Image2_ADD_Old = PatHis.Image2_ADD;
            string Image_ADD_Old = PatHis.Image_ADD;
            PatHis.PatientName = Request["txtName"].ToString();
            PatHis.PatientSex = Request.Form["selSex"] ?? "-1";
            PatHis.PatientAge = Request.Form["txtAge"].ToString();
            PatHis.PatientPhone = Request.Form["txtPhone"].ToString();
            PatHis.PatientId = Request.Form["txtID"].ToString();
            PatHis.PatientIdNum = Request.Form["txtCardID"].ToString();
            PatHis.PatientAddr = Request.Form["txtAddress"].ToString();
            PatHis.EmsDiseaseTime = Request.Form["dtDiseaseTime"].ToIsNULLDateTime1(0);
            PatHis.EMS_DISEASE_ADDR = Request.Form["txtillAddress"].ToString();
            PatHis.ConditionAssessment = Request.Form["ConditionAssessment"].ToString();
            PatHis.PatientArriveClass = Request["eventGrade"].ToString();
            PatHis.CarType = string.IsNullOrEmpty(Request["CarType"]) ? 0 : Convert.ToInt32(Request["CarType"]);
            PatHis.DoctorArriveTime = Request["txtDoctorArriveTime"].ToIsNULLDateTime1(0);
            PatHis.TransferOutHospital = Request["txtTransferOutHospital"];
            PatHis.ArriveDoorTime = Request["txtArriveDoorTime"].ToIsNULLDateTime1(0);
            PatHis.SureTransferOutTime = Request["txtSureTransferOutTime"].ToIsNULLDateTime1(0);
            PatHis.AmbulanceArriveTime = Request["txtAmbulanceArriveTime"];
            PatHis.LeaveTime = Request["txtLeaveHospitalTime"].ToIsNULLDateTime1(0);
            PatHis.DiseaseDep = Request["txtDiseaseDep"];
            PatHis.ConsultationTime = Request["txtConsultationTime"].ToIsNULLDateTime1(0);
            PatHis.LeaveDepTime = Request["txtLeaveDepRoomTime"].ToIsNULLDateTime1(0);
            PatHis.EmsArriveDoorTime = Request.Form["txtArriveTime"].ToIsNULLDateTime1(0);
            PatHis.HMedicalTime = Request.Form["txtReceiveTime"].ToIsNULLDateTime1(0);
            PatHis.IsRound = Request.QueryString["Bypass"].ToString();
            PatHis.ThroughToTime = Request.Form["txtArriveBypass"].ToIsNULLDateTime1(0);
            PatHis.ThroughToDep = Request["txthdnArriveKRoom"].ToString();
            PatHis.ThroughToTime = PatHis.ThroughToTime == null ? Request.Form["txtArriveDirect"].ToIsNULLDateTime1(0) : PatHis.ThroughToTime;
            PatHis.AMFirst_Institutions = Request.QueryString["FirstT"].ToString();
            PatHis.AMMedical_Name = Request.Form["txtNurse"].ToString();
            PatHis.AMBULANCE_Contact_Time = Request["txtFirstECGTime"].ToIsNULLDateTime1(0);
            //PatHis.PRE_ECG_TIME = Request["txtYqxdtTime"].ToIsNULLDateTime1(0);
            PatHis.AMEcg_Time = Request["txtYqxdtTime"].ToIsNULLDateTime1(0);
            PatHis.Delivery_Time = Request["txtDelivery_Time1"].ToIsNULLDateTime1(0);
            PatHis.Aspirin = Request["txtmgAspirin"].ToIsNULLDouble();
            PatHis.Ticagrelor = Request["txtmgTicagrelor"].ToIsNULLDouble();
            PatHis.Clopidogrel = Request["txtmgClopidogrel"].ToIsNULLDouble();
            PatHis.Rosuvastatin =  Request["txtmgRosuvastatin"].ToIsNULLDouble();
            PatHis.Atorvastatin =  Request["txtmgAtorvastatin"].ToIsNULLDouble();
            PatHis.Catheter_Ecg_Time = Request["txtCatheter_Ecg_Time"].ToIsNULLDateTime1(0);
            PatHis.Troponin_Blood_Time = Request["txtTroponin_Blood_Time"].ToIsNULLDateTime1(0);
            PatHis.First_Institutions = Request["FirstT2"];
            PatHis.Medical_Name = Request["txtMedical_Name"];
            PatHis.Contact_Time = Request["txtContact_Time"].ToIsNULLDateTime1(0);
            PatHis.Ecg_Confirmed_Time = Request["txtEcg_Confirmed_Time"].ToIsNULLDateTime1(0);
            PatHis.EcgConfirmTime = Request["txtECG_CONFIRM_TIME"].ToIsNULLDateTime1(0);
            PatHis.FirstDiagnosisTime = Request["txtFirstDiagnosisTime"].ToIsNULLDateTime1(0);
            PatHis.RoomMeetTime = Request["txtRoomMeetTime"].ToIsNULLDateTime1(0);
            PatHis.MeetRoomName = Request["txtMeetRoomName"];
            PatHis.DeliveryTime = Request["txtDelivery_Time2"].ToIsNULLDateTime1(0);
            PatHis.AspirinYn = Request["txtmgAspirin2"].ToIsNULLDouble();
            PatHis.TicagrelorYn = Request["txtmgTicagrelor2"].ToIsNULLDouble();
            PatHis.ClopidogrelYn = Request["txtmgClopidogrel2"].ToIsNULLDouble();
            PatHis.RosuvastatinYn =  Request["txtmgRosuvastatin2"].ToIsNULLDouble();
            PatHis.AtorvastatinYn =  Request["txtmgAtorvastatin2"].ToIsNULLDouble();
            PatHis.LeaveRoomTime = Request["txtLeaveRoomTime"].ToIsNULLDateTime1(0);
            PatHis.DeterminCatheterTime = Request["txtDeterminCatheterTime"].ToIsNULLDateTime1(0);
            PatHis.StartinforConsentTime = Request["txtStartinforConsentTime"].ToIsNULLDateTime1(0);
            PatHis.SigninforConsentTime = Request["txtSigninforConsentTime"].ToIsNULLDateTime1(0);
            PatHis.Enzyme = Request["txtEnzyme"].ToIsNULLInt(0);
            PatHis.Urokinase = Request["txtUrokinase"].ToIsNULLInt(0);
            PatHis.GuessD2BMins = Request["txtGuessD2BMins"].ToIsNULLInt(0).ToString();

            PatHis.Ecg_Time = Request["txtEcg_Time"].ToIsNULLDateTime1(0);
            PatHis.FirstHEcgTime = Request.Form["txtFirstECGTime"].ToIsNULLDateTime1(0);
            PatHis.Doubt_Radiology_NoticeTime = Request.Form["txtDoubt_Radiology_NoticeTime"].ToIsNULLDateTime1(0);
            PatHis.Doubt_Radiology_ArriveTime = Request.Form["txtDoubt_Radiology_ArriveTime"].ToIsNULLDateTime1(0);
            PatHis.Doubt_Radiography_Time = Request.Form["txtDoubt_Radiography_Time"].ToIsNULLDateTime1(0);
            PatHis.Doubt_Radiography_DIAGNOSISTime = Request.Form["txtDoubt_Radiography_DIAGNOSISTime"].ToIsNULLDateTime1(0);
            PatHis.Doubt_Radiography_DIAGNOSIS = Request.Form["txtDoubt_Radiography_DIAGNOSIS"];
            //三张图片 如果判断图片不通过则使用旧图片
            PatHis.Image1_ADD = (Request["txtfile1pass"].Equals("1") && CheckPicName(Request["txtImage1_ADD"])) ? Request["txtImage1_ADD"] : Image1_ADD_Old;//file1
            PatHis.Image2_ADD = (Request["txtfile2pass"].Equals("1") && CheckPicName(Request["txtImage2_ADD"])) ? Request["txtImage2_ADD"] : Image2_ADD_Old;//file2
            PatHis.Image_ADD = (Request["txtfile3pass"].Equals("1") && CheckPicName(Request["txtImage_ADD"])) ? Request["txtImage_ADD"] : Image_ADD_Old;//file3
            PatHis.IsEcgTransmission = Request.QueryString["LongRange"].ToString();
            PatHis.TransmissionClass = Request.Form["selTransType"] ?? "-1";
            PatHis.TransmissionTime = Request.Form["txtTransTime"].ToIsNULLDateTime1(0);
            PatHis.CardiologistName = Request.Form["txtXnkDoc"].ToString();
            PatHis.ConsultatTime = Request.Form["txtXnkTime"].ToIsNULLDateTime1(0);
            PatHis.StartCatheterTime = Request.Form["txtXnkTime2"].ToIsNULLDateTime1(0);
            PatHis.IsThrombolysis = Request.QueryString["thrombolysis"].ToIsNULLInt();
            PatHis.ThrombolysisAddr = Request.QueryString["thrombolysisAddr"].ToString();
            PatHis.ThrombolysisTime = Request.Form["txtthrombolysisTime"].ToIsNULLDateTime1(0);
            PatHis.ThrombolysisMedicine = Request.Form["txtthrombolysisMedi"].ToString();
            PatHis.ThrombolysisDose = Request.Form["txtthrombolysisMetering"].ToString();
            PatHis.PatientConsciousness = Request.QueryString["Conscious"].ToString();
            PatHis.PatientBreathe = Request.Form["txtBreath"].ToIsNULLInt();
            PatHis.PatientPulse = Request.Form["txtPulse"].ToIsNULLInt();
            PatHis.PatientHeart = Request.Form["txtHeartRate"].ToIsNULLInt();
            PatHis.PatientBloodH = Request.Form["txtBloodPressure"].ToIsNULLInt();
            PatHis.PatientBloodL = Request.Form["txtBloodPressure2"].ToIsNULLInt();
            PatHis.DrawBloodTime = Request.Form["txtDrawBloodTime"].ToIsNULLDateTime1(0);
            PatHis.ReportTime = Request.Form["txtReportingTime"].ToIsNULLDateTime1(0);
            PatHis.CtnlValue = Request.Form["txtcTnl"].ToString();
            PatHis.CtnlUnit = Request.Form["selcTnlUnit"] ?? "-1";
            PatHis.CtnlStatus = Request.Form["selcTnlType"].ToIsNULLInt(-1);
            PatHis.CtntValue = Request.Form["txtcTnT"].ToString();
            PatHis.CtntUnit = Request.Form["selcTnTUnit"] ?? "-1";
            PatHis.CtntStatus = Request.Form["selcTnTType"].ToIsNULLInt(-1);
            PatHis.CrValue = Request.Form["txtxqjg"].ToString();
            PatHis.CrUnit = Request.Form["selxqjgUnit"] ?? "-1";
            PatHis.DiagnosticPathId = Request.QueryString["PrelDiagnosis"].ToIsNULLInt();
            string customhtml = Request.Form["ContentList"].ToIsNULLString();
            customhtml = customhtml.Trim('☺');
            string[] list = customhtml.Split('☺');
            List<DiagnosticPathContent> CustomList = new List<DiagnosticPathContent>();
            DiagnosticPathContent content;
            foreach (string temp in list)
            {
                string[] control = temp.Split('¤');
                if (control != null && control.Length >= 2)
                {
                    content = new DiagnosticPathContent();
                    content.ControlId = control[0];
                    content.ControlContent = control[1];
                    content.ControlType = control[2].ToIsNULLInt();
                    content.ControlWidth = control[3].ToIsNULLInt();
                    content.ControlTitle = control[4];
                    content.ControlName = control[5];
                    content.ControlDescribe = control[6];
                    content.Options = control[7];
                    content.TimeFormart = control[8];
                    CustomList.Add(content);
                }
            }
            PatHis.ContentList = CustomList;
            PatHis.LeaveHospitalTime = Request.Form["txtOutTime"].ToIsNULLDateTime1(0);
            PatHis.TreatmentResultType = Request.QueryString["Treatment"].ToIsNULLInt();
            PatHis.TakeMedicineType = Request.Form["DischargeMedication"].ToIsNULLString();//多选，string
            PatHis.LeaveDoorTime = Request.Form["txtlkbydmsj"].ToIsNULLDateTime1(0);
            PatHis.TransferHospitalName = Request.Form["txtzwyy"].ToString();
            PatHis.TransferArriveTime = Request.Form["txtzdsj"].ToIsNULLDateTime1(0);
            PatHis.TransferReason = Request.Form["txtReason"].ToString();
            PatHis.IsPCI = Request.QueryString["YzPCI"].ToIsNULLInt();
            PatHis.IsDirectCatheter = Request.QueryString["Zddgs"].ToIsNULLInt();
            PatHis.TransferDepTime = Request.Form["txtZksj"].ToIsNULLDateTime1(0);
            PatHis.ReceptionTime = Request.Form["txtJzsj"].ToIsNULLDateTime1(0);
            PatHis.TransferDepReason = Request.Form["txtZkyyms"].ToString();
            PatHis.DieTime = Request.Form["txtDeadTime"].ToIsNULLDateTime1(0);
            PatHis.IsCardiogenic = Request.QueryString["Sfxyx"].ToIsNULLInt();
            PatHis.DieDescribe = Request.Form["txtDeadDescription"].ToString();
            PatHis.UpdateUserId = loginUser.Personnel_id;
            string Json = JsonConvert.SerializeObject(PatHis);
            OperateResult resultInfo2 = MedicalRecordsManager.SetCaseHistory(Json);
            if (resultInfo2.Result == 1)
            {
                ConfigurationManager.RefreshSection("appSettings");
                string picVirPath = ConfigurationManager.AppSettings["ImageUploadPath"].ToString();
                if (!string.IsNullOrWhiteSpace(Image1_ADD_Old) && !string.IsNullOrWhiteSpace(PatHis.Image1_ADD) && !Image1_ADD_Old.Equals(PatHis.Image1_ADD))
                    System.IO.File.Delete(Server.MapPath(picVirPath + Image1_ADD_Old));
                if (!string.IsNullOrWhiteSpace(Image2_ADD_Old) && !string.IsNullOrWhiteSpace(PatHis.Image2_ADD) && !Image2_ADD_Old.Equals(PatHis.Image2_ADD))
                    System.IO.File.Delete(Server.MapPath(picVirPath + Image2_ADD_Old));
                if (!string.IsNullOrWhiteSpace(Image_ADD_Old) && !string.IsNullOrWhiteSpace(PatHis.Image_ADD) && !Image_ADD_Old.Equals(PatHis.Image_ADD))
                    System.IO.File.Delete(Server.MapPath(picVirPath + Image_ADD_Old));
            }
            return Content(resultInfo2.Body.ToString());
        }

        /// <summary>
        /// 检测图片文件名
        /// </summary>
        /// <param name="picName"></param>
        /// <returns></returns>
        public bool CheckPicName(string picName)
        {
            if (string.IsNullOrWhiteSpace(picName)) return false;
            if (picName.IndexOf(".") <= 0) return false;
            string[] picNameArr = picName.Split('.');
            if (picNameArr.Length < 2) return false;
            string ext = picNameArr[picNameArr.Length - 1];
            ext = ext.ToLower();
            if (ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "gif" || ext == "bmp")
                return true;
            return false;
        }

        /// <summary>
        /// 打印报表
        /// </summary>
        /// <returns></returns>
        public ActionResult EventPrint()
        {
            string pid = WebUtils.GetString("pid");
            if (string.IsNullOrWhiteSpace(pid))
                return Content("缺少ID参数");
            ViewBag.pid = pid;
            return View();
        }
        /// <summary>
        /// 获取科室下拉列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDropRoomList()
        {
            string key = Request["key"];
            string list = Request["list"];
            if (!string.IsNullOrEmpty(list))
                return JsonDate(GetCheckDropList(list, key));
            OperateResult result = MedicalRecordsManager.GetDepartmentName();
            if (result.Result == 1)
            {
                ViewBag.RoomList = JsonConvert.SerializeObject(result.Body);
                return JsonDate(result.Body);
            }
            return Content("");
        }
        /// <summary>
        /// 获取医生和护士综合下拉列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDropDocNurList()
        {
            string key = Request["key"];
            string list = Request["list"];
            if (!string.IsNullOrEmpty(list))
                return JsonDate(GetCheckDropList(list, key));
            OperateResult result = MedicalRecordsManager.GetUserName(string.Empty);
            if (result.Result == 1)
            {
                ViewBag.DocNurList = JsonConvert.SerializeObject(result.Body);
                return JsonDate(result.Body);
            }
            return Content("");
        }
        /// <summary>
        /// 获取医生下拉列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDropDoctorList()
        {
            string key = Request["key"];
            string list = Request["list"];
            if (!string.IsNullOrEmpty(list))
                return JsonDate(GetCheckDropList(list, key));
            OperateResult result = MedicalRecordsManager.GetUserName("医生");
            if (result.Result == 1)
            {
                ViewBag.DoctorList = JsonConvert.SerializeObject(result.Body);
                return JsonDate(result.Body);
            }
            return Content("");
        }
        /// <summary>
        /// 获取护士下拉列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDropNurseList()
        {
            string key = Request["key"];
            string list = Request["list"];
            if (!string.IsNullOrEmpty(list))
                return JsonDate(GetCheckDropList(list, key));
            OperateResult result = MedicalRecordsManager.GetUserName("护士");
            if (result.Result == 1)
            {
                ViewBag.NurseList = JsonConvert.SerializeObject(result.Body);
                return JsonDate(result.Body);
            }
            return Content("");
        }
        /// <summary>
        /// 动态加载下拉列表 实时搜索
        /// </summary>
        /// <param name="list">源数据</param>
        /// <param name="key">搜索值</param>
        /// <returns></returns>
        private List<DropItem> GetCheckDropList(string list, string key)
        {
            if (string.IsNullOrEmpty(list))
                return new List<DropItem>();
            var doctorlist2 = JsonConvert.DeserializeObject<List<DropItem>>(HttpUtility.UrlDecode(list));
            if (!string.IsNullOrEmpty(key))
                return doctorlist2.Where(p => p.Name.Contains(key)).ToList();
            return doctorlist2;
        }

        public ActionResult Patients() {
            return View();
        }
    }
    public class DropItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}